﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.DomainObject.Technology;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Technology.Interface;

namespace WMS.FC.Domain.Service.Technology
{
    public class AddTechnologyRouteProcessService : ServiceBase, IAddTechnologyRouteProcessService
    {
        protected readonly ITechnologyRepository technologyRepository;

        public AddTechnologyRouteProcessService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
        }

        public async Task<ActionResultBase> AddTechnologyRouteProcess(TechnologyRouteProcessDO? dO, UserInfo userInfo)
        {
            var result = new ActionResultBase("新增工艺路径工序");
            try
            {
                if (dO == null)
                    return result.ArgumentError("工艺路径工序数据不能为空");

                var technologyRouteProcessPOList = await technologyRepository.GetTechnologyRouteProcessList(dO.TechnologyRouteCode);
                var technologyRouteProcess = mapper.Map<TechnologyRouteProcessPO>(dO);
                var count = 0;
                if (dO.SortNumber == null || dO.SortNumber <= 0 || dO.SortNumber > technologyRouteProcessPOList.Count)
                {
                    technologyRouteProcess.SortNumber = technologyRouteProcessPOList.Count + 1;
                    technologyRouteProcess.WarehouseCode = options.Value.WarehouseCode;
                    count = await technologyRepository.Insert(technologyRouteProcess, userInfo);
                }
                else
                {
                    technologyRouteProcessPOList.Insert(dO.SortNumber.Value - 1, technologyRouteProcess);
                    for (var i = 0; i < technologyRouteProcessPOList.Count; i++)
                    {
                        technologyRouteProcessPOList[i].SortNumber = i + 1;
                    }

                    count = await technologyRepository.Insert(technologyRouteProcess, userInfo);
                    count += await technologyRepository.Update(technologyRouteProcessPOList, userInfo);
                }

                if (count == 0)
                    return result.DbError("新增工艺路径工序异常");

                result.Message = "新增数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
